/**
 * Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.zouqone.smc.modules.sys.web;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.zouqone.smc.common.config.Global;
import com.zouqone.smc.common.persistence.Page;
import com.zouqone.smc.common.utils.StringUtils;
import com.zouqone.smc.common.web.BaseController;
import com.zouqone.smc.modules.sys.entity.Menu;
import com.zouqone.smc.modules.sys.service.MenuService;
import com.zouqone.smc.modules.sys.service.SystemService;
import com.zouqone.smc.modules.sys.utils.UserUtils;

/**
 * 菜单Controller
 * @author ThinkGem
 * @version 2013-3-23
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/menu")
public class MenuController extends BaseController {

	@Autowired
	private SystemService systemService;
	
	@Autowired
	private MenuService menuService;
	
	@ModelAttribute("menu")
	public Menu get(@RequestParam(required=false) String id) {
		if (StringUtils.isNotBlank(id)){
			return systemService.getMenu(id);
		}else{
			return new Menu();
		}
	}

	@RequiresPermissions("sys:menu:view")
	@RequestMapping(value = {"index"})
	public String indexPage(Menu menu, HttpServletRequest request, HttpServletResponse response, Model model) {
		model.addAttribute("menu", menu);
		return "modules/sys/menu/menuIndex";
	}

	@RequiresPermissions("sys:menu:view")
	@RequestMapping(value = {"listMenu"})
	public String listMenu(Menu menu, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Menu> pageEntity = new Page<Menu>(request, response);
		if(menu!=null && !StringUtils.isEmpty(menu.getOrderBy()) && !StringUtils.isEmpty(menu.getSortType())){
        	pageEntity.setOrderBy("a."+menu.getOrderBy() +" "+menu.getSortType()+" ");
        }
		Page<Menu> page = menuService.findPage(pageEntity, menu); 
		model.addAttribute("page", page);
		return "modules/sys/menu/menuList";
	}

	@RequiresPermissions("sys:menu:view")
	@RequestMapping(value = "formMenu")
	public String formMenu(Menu menu,HttpServletRequest request, Model model) {
		if(menu!=null){
			if(menu.getParent()!=null && !StringUtils.isEmpty(menu.getParent().getId()) && StringUtils.isEmpty(menu.getParent().getName())){
				Menu parent = menuService.get(menu.getParent()) ;
				menu.setParent(parent);
			}else if (menu.getParent()==null || StringUtils.isEmpty(menu.getParent().getId())){
				menu.setParent(new Menu(Menu.getRootId()));
			}
		}
		model.addAttribute("menu", menu);
		model.addAttribute("opt",request.getParameter("opt"));
		return "modules/sys/menu/menuForm";
	}

	@RequiresPermissions("sys:menu:edit")
	@RequestMapping(value = "saveMenu")
	public String saveMenu(Menu menu,HttpServletRequest request, Model model, RedirectAttributes redirectAttributes) {
		if(!UserUtils.getUser().isAdmin()){
			addMessage(redirectAttributes, "越权操作，只有超级管理员才能添加或修改数据！");
			return "redirect:" + adminPath + "/sys/role/?repage";
		}
		if(Global.isDemoMode()){
			addMessage(redirectAttributes, "演示模式，不允许操作！");
			return "redirect:" + adminPath + "/sys/menu/menuForm";
		}
		if (!beanValidator(model, menu)){
			return formMenu(menu,request, model);
		}
		systemService.saveMenu(menu);
		//menuService.save(menu);
		model.addAttribute("menu", menu);
		model.addAttribute("opt","save");
		model.addAttribute("message","保存菜单(" + menu.getName() + ")成功");
		return "modules/sys/menu/menuForm";
	}
	
	/**
	 * 批量修改排序
	 **/
	@RequiresPermissions("sys:menu:edit")
	@RequestMapping(value = "updateMenuSort")
	public String updateMenuSort(String[] ids, Integer[] sorts,Menu parent,HttpServletRequest request, RedirectAttributes redirectAttributes) {
		if(Global.isDemoMode()){
			addMessage(redirectAttributes, "演示模式，不允许操作！");
			return "redirect:" + adminPath + "/sys/menu/";
		}
		if(sorts == null || sorts.length == 0 ||ids == null ||ids.length == 0){
    		addMessage(redirectAttributes, "更新顺序失败");
    	}else{
    		for (int i = 0; i < ids.length; i++) {
        		Menu menu = new Menu(ids[i]);
        		menu.setSort(sorts[i]);
        		systemService.updateMenuSort(menu);
        	}
	    	addMessage(redirectAttributes, "更新顺序成功");
    	}
		redirectAttributes.addAttribute("parent.id", request.getParameter("parent.id"));
		return "redirect:"+Global.getAdminPath()+"/sys/menu/listMenu?repage";
	}
	
	
	
	

	// sys menu
	
	@RequiresPermissions("sys:menu:view")
	@RequestMapping(value = {"list", ""})
	public String list(Model model) {
		List<Menu> list = Lists.newArrayList();
		List<Menu> sourcelist = systemService.findAllMenu();
		Menu.sortList(list, sourcelist, Menu.getRootId(), true);
        model.addAttribute("list", list);
		return "modules/sys/menuList";
	}

	@RequiresPermissions("sys:menu:view")
	@RequestMapping(value = "form")
	public String form(Menu menu, Model model) {
		if (menu.getParent()==null||menu.getParent().getId()==null){
			menu.setParent(new Menu(Menu.getRootId()));
		}
		menu.setParent(systemService.getMenu(menu.getParent().getId()));
		// 获取排序号，最末节点排序号+30
		if (StringUtils.isBlank(menu.getId())){
			List<Menu> list = Lists.newArrayList();
			List<Menu> sourcelist = systemService.findAllMenu();
			Menu.sortList(list, sourcelist, menu.getParentId(), false);
			if (list.size() > 0){
				menu.setSort(list.get(list.size()-1).getSort() + 30);
			}
		}
		model.addAttribute("menu", menu);
		return "modules/sys/menuForm";
	}
	
	@RequiresPermissions("sys:menu:edit")
	@RequestMapping(value = "save")
	public String save(Menu menu, Model model, RedirectAttributes redirectAttributes) {
		if(!UserUtils.getUser().isAdmin()){
			addMessage(redirectAttributes, "越权操作，只有超级管理员才能添加或修改数据！");
			return "redirect:" + adminPath + "/sys/role/?repage";
		}
		if(Global.isDemoMode()){
			addMessage(redirectAttributes, "演示模式，不允许操作！");
			return "redirect:" + adminPath + "/sys/menu/";
		}
		if (!beanValidator(model, menu)){
			return form(menu, model);
		}
		systemService.saveMenu(menu);
		addMessage(redirectAttributes, "保存菜单'" + menu.getName() + "'成功");
		return "redirect:" + adminPath + "/sys/menu/";
	}
	
	@RequiresPermissions("sys:menu:edit")
	@RequestMapping(value = "delete")
	public String delete(Menu menu, RedirectAttributes redirectAttributes) {
		if(Global.isDemoMode()){
			addMessage(redirectAttributes, "演示模式，不允许操作！");
			return "redirect:" + adminPath + "/sys/menu/";
		}
//		if (Menu.isRoot(id)){
//			addMessage(redirectAttributes, "删除菜单失败, 不允许删除顶级菜单或编号为空");
//		}else{
			systemService.deleteMenu(menu);
			addMessage(redirectAttributes, "删除菜单成功");
//		}
		return "redirect:" + adminPath + "/sys/menu/";
	}

	@RequiresPermissions("sys:menu:edit")
	@RequestMapping(value = "batchDelete")
	public String delete(String ids, RedirectAttributes redirectAttributes) {
		menuService.delete(ids);
		addMessage(redirectAttributes, "删除菜单管理成功");
		return "redirect:"+Global.getAdminPath()+"/sys/menu/?repage";
	}
	
	@RequiresPermissions("user")
	@RequestMapping(value = "tree")
	public String tree() {
		return "modules/sys/menu/menuTree";
	}

	@RequiresPermissions("user")
	@RequestMapping(value = "treeselect")
	public String treeselect(String parentId, Model model) {
		model.addAttribute("parentId", parentId);
		return "modules/sys/menu/menuTreeselect";
	}
	
	/**
	 * 批量修改菜单排序
	 */
	@RequiresPermissions("sys:menu:edit")
	@RequestMapping(value = "updateSort")
	public String updateSort(String[] ids, Integer[] sorts, RedirectAttributes redirectAttributes) {
		if(Global.isDemoMode()){
			addMessage(redirectAttributes, "演示模式，不允许操作！");
			return "redirect:" + adminPath + "/sys/menu/";
		}
    	for (int i = 0; i < ids.length; i++) {
    		Menu menu = new Menu(ids[i]);
    		menu.setSort(sorts[i]);
    		systemService.updateMenuSort(menu);
    	}
    	addMessage(redirectAttributes, "保存菜单排序成功!");
		return "redirect:" + adminPath + "/sys/menu/";
		/*
		if(sorts == null || sorts.length == 0 ||ids == null ||ids.length == 0){
    		addMessage(redirectAttributes, "更新顺序失败");
    	}else{
    		int len = ids.length;
	    	Menu[] entitys = new Menu[len];
	    	for (int i = 0; i < len; i++) {
	    		entitys[i] = menuService.get(ids[i]);
	    		entitys[i].setSort(sorts[i]);
	    		menuService.save(entitys[i]);
	    	}
	    	addMessage(redirectAttributes, "更新顺序成功");
    	}
		return "redirect:"+Global.getAdminPath()+"/sys/menu/?repage";
		*/
	}
	
	
	/**
	 * isShowHide是否显示隐藏菜单
	 * @param extId
	 * @param isShowHidden
	 * @param response
	 * @return
	 */
	@RequiresPermissions("user")
	@ResponseBody
	@RequestMapping(value = "treeData")
	public List<Map<String, Object>> treeData(@RequestParam(required=false) String extId,@RequestParam(required=false) String isShowHide, HttpServletResponse response) {
		List<Map<String, Object>> mapList = Lists.newArrayList();
		List<Menu> list = systemService.findAllMenu();
		for (int i=0; i<list.size(); i++){
			Menu e = list.get(i);
			if (StringUtils.isBlank(extId) || (extId!=null && !extId.equals(e.getId()) && e.getParentIds().indexOf(","+extId+",")==-1)){
				if(isShowHide != null && isShowHide.equals("0") && e.getIsShow().equals("0")){
					continue;
				}
				Map<String, Object> map = Maps.newHashMap();
				map.put("id", e.getId());
				map.put("pId", e.getParentId());
				map.put("name", e.getName());
				mapList.add(map);
			}
		}
		return mapList;
	}
	
	@RequiresPermissions("sys:menu:edit")
	@ResponseBody
	@RequestMapping(value = "ajaxDelete")
	public Map<String, String> ajaxDelete(String ids,HttpServletRequest request, HttpServletResponse response) {
		Map<String, String> map = new HashMap<String, String>();
		if(Global.isDemoMode()){
			map.put("success", "0");
			map.put("message", "演示模式，不允许操作！");
			return map;
		}
//		if (Menu.isRoot(id)){
//			addMessage(redirectAttributes, "删除菜单失败, 不允许删除顶级菜单或编号为空");
//		}else{
			//systemService.deleteMenu(menu);
//		}
		try {
			menuService.delete(ids);
			map.put("message", "删除成功");
			map.put("success", "1");
		} catch (Exception e) {
			// TODO: handle exception
			map.put("message", "删除失败！");
			map.put("success", "0");
			return map;
		}
		return map;
	}
}
